package com.a0soft.gphone.aTruffleHog.scrsht;
/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 3, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * Copyright(C) 2011 
 *   Sam Lu <ysl.sam.lu (at) gmail.com>
 *
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.a0soft.gphone.aTruffleHog.R;
import com.a0soft.gphone.aTruffleHog.gio.util.UIUtils;
import com.a0soft.gphone.aTruffleHog.util.MiscUtil;
import com.a0soft.gphone.aTruffleHog.util.Wrapper;
import com.a0soft.gphone.aTruffleHog.util.aDebug;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class Screenshot {
    private static boolean m_bTaking;
    
	private static final String LOG_TAG = Screenshot.class.getSimpleName();
	
	public static void
	TakeScreenshot(Activity act)
	{
	    if (m_bTaking)
	        return;
	    
		final Context ctx = act;
        
		ViewGroup vgDecor = (ViewGroup)act.getWindow().getDecorView();
        if (vgDecor == null) {
            if (aDebug.ENABLED)
                aDebug.e(LOG_TAG, "TakeScreenshot(): vgDecor is null!");
            return;
        }
        ViewGroup vgContent = (ViewGroup)vgDecor.findViewById(android.R.id.content);
        if (vgContent == null) {
            if (aDebug.ENABLED)
                aDebug.e(LOG_TAG, "TakeScreenshot(): vgContent is null!");
            return;
        }
        
        View vTop;		
		if (MiscUtil.GetSDKVersion() >= 11) {
		    //also include action bar
		    if (UIUtils.isTablet(act))
	            vTop = vgDecor; 
		    else
		        vTop = vgDecor.getChildAt(0); //skip status bar
		}
		else {
		    vTop = vgContent.getChildAt(0); //skip status bar
		}
        if (vTop == null) {
            if (aDebug.ENABLED)
                aDebug.e(LOG_TAG, "TakeScreenshot(): vTop is null!");
            return;
        }
        
        m_bTaking = true;
		new TakeScreenshotTask(ctx, vTop).execute();
	}
	
	private static class TakeScreenshotTask extends AsyncTask<Void, Void, String> {
        private Context m_ctx;
        private View    m_vTop;
	    private Bitmap  m_bmp;
	    
	    TakeScreenshotTask(Context ctx, View vTop)
	    {
	        m_ctx = ctx;
	        m_vTop = vTop;
	    }

	    @Override protected String 
	    doInBackground(Void... objs) 
	    {
	        return _SaveScreenshot(m_ctx, m_bmp);
	    }
         
        @Override protected void 
        onPreExecute()
        {
            Toast.makeText(m_ctx, R.string.wait, Toast.LENGTH_SHORT).show();
            
            final int nWidth = m_vTop.getWidth(); 
            final int nHeight = m_vTop.getHeight();
            
            m_bmp = Bitmap.createBitmap(nWidth, nHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(m_bmp);
            m_vTop.draw(canvas);
        }

        @Override protected void 
	    onPostExecute(String strFilename) 
	    {   
            m_bmp.recycle();
            m_bmp = null;
            m_vTop = null;
            
            m_bTaking = false;

            if (strFilename == null) {
	            new AlertDialog.Builder(m_ctx)
	                .setIcon(android.R.drawable.ic_dialog_alert)
	                .setTitle(R.string.screenshot_no_sd_title)
	                .setMessage(R.string.screenshot_no_sd)
	                .setNegativeButton(android.R.string.ok, null)
	                .show();
	        }
	         
	        Intent it = new Intent(m_ctx, ScreenshotShareWnd.class);
	        it.putExtra(ScreenshotShareWnd.KEY_FILENAME, strFilename);
	        m_ctx.startActivity(it);
	    }
	 }
	
	private static String
	_SaveScreenshot(Context ctx, Bitmap bmp)
	{
		Date d = new Date(System.currentTimeMillis());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_kk-mm-ss", Locale.ENGLISH);
        df.setTimeZone(TimeZone.getDefault());
        String strFileName = df.format(d) + ".jpg";
        
        File fScreenshot = _SaveBitmapToFile(ctx, bmp, strFileName);
        if (fScreenshot == null) 
        	return null;
		
        return fScreenshot.getPath();
	}
	
	private static File
	_SaveBitmapToFile(Context ctx, Bitmap bmp, String strFilename)
	{
		File fFile = _CreatePictureFile(ctx, strFilename);
		if (fFile == null)
			return null;
		
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(fFile);
			bmp.compress(CompressFormat.PNG, 100, fos);
	        fos.close();
	        return fFile;
		} catch (FileNotFoundException e) {
			if (aDebug.ENABLED) {
			    aDebug.d(LOG_TAG, "_SaveBitmapToFile()", e);
			}
		} catch (IOException e) {			
			if (aDebug.ENABLED) {
			    aDebug.d(LOG_TAG, "_SaveBitmapToFile()", e);
			}
		}
		return null;
	}

	private static File
	_CreatePictureFile(Context ctx, String strFilename)
	{
	    File fPicDir = Wrapper.GetExternalFilesDir(ctx, "screenshot");
	    if (fPicDir == null)
	        return null;
	    
        if (!fPicDir.exists()) {
        	fPicDir.mkdirs();
        }
        if (!fPicDir.isDirectory()) {
            if (aDebug.ENABLED)
                aDebug.d(LOG_TAG, fPicDir.getAbsolutePath() + " is not a directory");
            return null;
        }

        if (strFilename != null) {
			File fFile = new File(fPicDir, strFilename);
			return fFile;
        }
        else {
        	return fPicDir;
        }
	}
}
